from enum import Enum

from loguru import logger
from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.school.processor.base_processor import BaseProcessor, ImgType
from com.arcfox.util import util
from com.arcfox.middleware import cos_middleware as cos
from com.arcfox.util.constant import COS_BUCKET_SCHOOL_IMG


class YZYSchoolImgProcessor(BaseProcessor):
    def __init__(self):
        self.URL_SOURCE = "YZY"

    def parse_all_img(self, result_json):
        result = result_json['result']
        img_list = []
        for item in result['urls']:
            img_desc = item['description']
            img_url = item['url']
            img_type = ImgType.SCENERY
            if item['isBanner']:
                img_type = ImgType.BANNER
            img_list.append({"url": img_url, "img_desc": img_desc, "img_type": img_type})
        img_list.append({"url": result['logoUrl'], "img_desc": "校徽", "img_type": ImgType.LOGO})
        return img_list

    async def save_img(self, task, img, img_buffer):
        uid = task['university_uid']
        file_name = f"{uid}/{util.get_md5(img['url'])}.jpg"
        cos.upload_by_bytes(file_name, img_buffer, COS_BUCKET_SCHOOL_IMG)
        logger.info(f"{file_name} saved!")
        mapping = db.MysqlMapping("tb_university_img")
        result = await mapping.query({"university_uid": uid, "img_url": file_name}, ["id"])
        if result:
            logger.info("图片已存在!")
        else:
            data = {
                "university_uid": uid,
                "university_name": task['university_name'],
                "img_url": file_name,
                "img_type": img['img_type'].value,
                "img_desc": img['img_desc'],
                "img_source": self.URL_SOURCE,
            }
            await mapping.insert(data)

